package com.unieagle.exam.ui;

import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.DrawerLayout.DrawerListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.TextView;

import com.unieagle.exam.R;
import com.unieagle.exam.db.DatabaseContext;
import com.unieagle.exam.db.ExamDBHelper;
import com.unieagle.exam.model.Answer;
import com.unieagle.exam.model.Exam;
import com.unieagle.exam.model.Question;
import com.unieagle.exam.utils.SharedPreferenceUtils;
import com.unieagle.exam.utils.UIUtils;
import com.unieagle.exam.widget.SmallCheckBox;

/**
 * 复卷页面
 * @author QianJing
 *
 */

public class ExamResultDetailActivity extends BaseActivity {
	
	private String[] INDEX = {"A", "B", "C", "D", "E", "F", "G", "H", "I"};
	
	private int currentIndex = 0, questionCnt = 0;
	
	private final static int VOLUMN_CNT = 4;
	
	private ListView mListView;
	
	private QuestionIndexAdapter mAdapter;
	
	private TextView mTvType, mTvContent, mTvCorrectAns, mTvUserChoice;
	
	private ViewGroup mVGAnswer;
	
	private List<Question> mQuesions;
	
	private Button mBtnPre, mBtnNext, mBtnErrorExam;
	
	private DrawerLayout mDrawerLayout;
	
	private ImageView mIvDrawer;
	
	private Exam mExam;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.exam_resutl_detail_layout);
		init();
	}
	
	protected void init() {
		super.init();
		if(getIntent().getBooleanExtra("from_error_result", false)) {
			mTvTitle.setText(R.string.error_exam_detail);
		} else {
			mTvTitle.setText(R.string.review);
		}
		mListView = (ListView)findViewById(R.id.list);
		mTvContent = (TextView)findViewById(R.id.content);
		mTvType = (TextView)findViewById(R.id.type);
		mTvUserChoice = (TextView)findViewById(R.id.user_choice);
		mTvCorrectAns = (TextView)findViewById(R.id.correct_ans);
		mVGAnswer = (ViewGroup)findViewById(R.id.answer);
		mAdapter = new QuestionIndexAdapter(this);
		mListView.setAdapter(mAdapter);
		mExam = (Exam)getIntent().getParcelableExtra("exam");
		mQuesions= mExam.getQuestions();
		questionCnt = mQuesions.size();
		mBtnPre = (Button) findViewById(R.id.pre);
		mBtnNext = (Button) findViewById(R.id.next);
		mBtnPre.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				currentIndex--;
				if(mQuesions.get(currentIndex).isBlank()) {
					for(int i = currentIndex; i >= 0; i--) {
						if(!mQuesions.get(i).isBlank()) {
							currentIndex = i;
							break;
						}
					}
				}
				initPreAndNextButton();
				showQuestion(currentIndex);
				showAnswer(currentIndex);
			}
		});
		mBtnNext.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				currentIndex++;
				if(mQuesions.get(currentIndex).isBlank()) {
					for(int i = currentIndex; i < mQuesions.size(); i++) {
						if(!mQuesions.get(i).isBlank()) {
							currentIndex = i;
							break;
						}
					}
				}
				initPreAndNextButton();
				showQuestion(currentIndex);
				showAnswer(currentIndex);
			}
		});
		mBtnErrorExam = (Button)findViewById(R.id.error_exam);
		mBtnErrorExam.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				errorExam();
			}
		});
		showQuestion(0);
		showAnswer(0);
		mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
		mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
		mDrawerLayout.setScrimColor(Color.TRANSPARENT);
		mDrawerLayout.setDrawerListener(new DrawerListener() {
			
			@Override
			public void onDrawerStateChanged(int arg0) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onDrawerSlide(View arg0, float arg1) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onDrawerOpened(View arg0) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onDrawerClosed(View arg0) {
				mIvDrawer.setVisibility(View.VISIBLE);
			}
		});
		mIvDrawer = (ImageView) findViewById(R.id.drawer);
		mIvDrawer.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				mIvDrawer.setVisibility(View.GONE);
				mDrawerLayout.openDrawer(mListView);
			}
		});
	}
	
	private int calBlankCnt(int index) {
		int cnt = 0;
		for(int i = 0; i < index; i++) {
			if(mQuesions.get(i).isBlank()) {
				cnt++;
			}
		}
		return cnt;
	}
	
	class QuestionIndexAdapter extends BaseAdapter {
		
		private LayoutInflater inflator;
		
		public QuestionIndexAdapter(Context ctx) {
			inflator = LayoutInflater.from(ctx);
		}

		@Override
		public int getCount() {
			return questionCnt / 4 + ((questionCnt % 4) == 0 ? 0 : 1);
		}

		@Override
		public Object getItem(int arg0) {
			return arg0 * VOLUMN_CNT;
		}

		@Override
		public long getItemId(int arg0) {
			return arg0;
		}

		@Override
		public View getView(int arg0, View convertView, ViewGroup arg2) {
			ViewHolder holder;
			if (convertView == null) {
				convertView = inflator.inflate(R.layout.exam_activity_lisitem, null);
				holder = new ViewHolder();
				holder.holder = new Button[VOLUMN_CNT];
				holder.holder[0] = (Button) convertView.findViewById(R.id.q_1);
				holder.holder[1] = (Button) convertView.findViewById(R.id.q_2);
				holder.holder[2] = (Button) convertView.findViewById(R.id.q_3);
				holder.holder[3] = (Button) convertView.findViewById(R.id.q_4);
				holder.title = (TextView)convertView.findViewById(R.id.title);
				convertView.setTag(holder);
			}else {
				holder = (ViewHolder) convertView.getTag();
			}
			int first = arg0 * VOLUMN_CNT;
			if(first == 0) {
				holder.title.setVisibility(View.VISIBLE);
				if(!mQuesions.get(0).isRequired()) {
					holder.title.setText(mQuesions.get(0).getTypeName());
				} else {
					holder.title.setText("必知必会题");
				}
			} else if(mQuesions.get(first).isRequired() && mQuesions.get(first - 1).isRequired()) {
				holder.title.setVisibility(View.GONE);
			} else if(mQuesions.get(first - 1).isBlank() || 
					!mQuesions.get(first - 1).getType().equals(mQuesions.get(first).getType())){
				holder.title.setVisibility(View.VISIBLE);
				holder.title.setText(mQuesions.get(first).getTypeName());
			} else {
				holder.title.setVisibility(View.GONE);
			}
			for(int i = 0; i < VOLUMN_CNT; i++) {
				final int index = arg0 * VOLUMN_CNT + i;
				if(index > mQuesions.size() - 1 || mQuesions.get(index).isBlank()) {
					holder.holder[i].setVisibility(View.INVISIBLE);
				} else {
					holder.holder[i].setVisibility(View.VISIBLE);
					holder.holder[i].setText(String.valueOf(index + 1 - calBlankCnt(index))); 
					if(!mQuesions.get(index).isAnswered()) {
						holder.holder[i].setBackgroundColor(Color.rgb(189, 191, 191));
					}else if(mQuesions.get(index).isCorrect()){
						holder.holder[i].setBackgroundColor(Color.rgb(126, 219, 133));
					} else {
						holder.holder[i].setBackgroundColor(Color.rgb(247, 161, 67));
					}
					holder.holder[i].setOnClickListener(new View.OnClickListener() {
						
						@Override
						public void onClick(View arg0) {
							currentIndex = index;
							initPreAndNextButton();
							showQuestion(currentIndex);
							showAnswer(currentIndex);
							mIvDrawer.setVisibility(View.VISIBLE);
							mDrawerLayout.closeDrawer(mListView);
							mAdapter.notifyDataSetChanged();
						}
					});
				}
			}
			return convertView;
		}
		
		class ViewHolder {
			Button[] holder;
			TextView title;
		}
		
	}
	
	private void initPreAndNextButton() {
		int realIndex = currentIndex - calBlankCnt(currentIndex);
		if(realIndex >= questionCnt - 1) {
			mBtnNext.setVisibility(View.GONE);
		} else {
			mBtnNext.setVisibility(View.VISIBLE);
		}
		if(realIndex <= 0) {
			mBtnPre.setVisibility(View.GONE);
		} else {
			mBtnPre.setVisibility(View.VISIBLE);
		}
	}
	
	private void showQuestion(int index) {
		Question q = mQuesions.get(index);
		mTvContent.setText(String.format("第%d题    %s", currentIndex + 1 - calBlankCnt(currentIndex), q.getContent()));
		if(q.isRequired()) {
			mTvType.setText(R.string.required);
			mTvType.setBackgroundResource(R.drawable.bg_required);
		} else if(q.getType().equals("single_choice")) {
			mTvType.setText(R.string.single_choice);
			mTvType.setBackgroundResource(R.drawable.bg_single_choice);
		} else if(q.getType().equals("judge")) {
			mTvType.setText(R.string.judge);
			mTvType.setBackgroundResource(R.drawable.bg_judge);
		} else {
			mTvType.setText(R.string.multi_choice);
			mTvType.setBackgroundResource(R.drawable.bg_single_choice);
		}
	}
	
	private void showAnswer(int index) {
		Question q = mQuesions.get(index);
		List<Answer> list = q.getAnswer();
		if(list.size() == 0) {
			ExamDBHelper helper = new ExamDBHelper(new DatabaseContext(this));
			list.addAll(helper.getAnswer((int)q.getId()));
		}
		mVGAnswer.removeAllViews();
		for(int i = 0; i < list.size(); i++) {
			addAnswer(q, list.get(i), i);
		}
		showUserAnswer(index);
	}
	
	private void addAnswer(Question q, Answer ans, int index) {
		SmallCheckBox cb = new SmallCheckBox(this);
		LayoutParams p = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		p.bottomMargin = UIUtils.dip2px(this, 12.5);
		cb.setTextColor(Color.BLACK);
		cb.setTextSize(15.0f);
		cb.setText(String.format("%s  %s", INDEX[index],ans.getContent()));
		cb.setHeight(UIUtils.dip2px(this, 32));
		cb.setWidth(UIUtils.dip2px(this, 300));
		cb.setClickable(false);
		cb.setBackgroundColor(Color.rgb(225, 225, 220));
		((LinearLayout)mVGAnswer).addView(cb, p);
	}
	
	private void showUserAnswer(int index) {
		Question q = mQuesions.get(index);
		List<Answer> user_ans = q.getChoose();
		List<Answer> answer = q.getAnswer();
		String error_times = "本题您总共答错过" + SharedPreferenceUtils.
				getErrorCount(ExamResultDetailActivity.this, q.getId())+ "次"; 
		StringBuffer answer_content = new StringBuffer();
		StringBuffer correct_answer_content = new StringBuffer();
		if(answer.size() == 0) {
			ExamDBHelper helper = new ExamDBHelper(new DatabaseContext(this));
			answer.addAll(helper.getAnswer((int)q.getId()));
		}
		if(user_ans!= null && user_ans.size() == 0) {
			mTvUserChoice.setText("本题您未作答 " + error_times);
		}else {
			for(int i = 0; i < answer.size(); i++) {
				if(user_ans.contains(answer.get(i))) {
					answer_content.append(INDEX[i]).append("、");
				}
			}
			answer_content.deleteCharAt(answer_content.length() - 1);
			mTvUserChoice.setText("本题您选择的答案是" + answer_content + "  " +error_times);
		}
		if(!q.isCorrect()) {
			mTvUserChoice.setTextColor(Color.RED);
		} else {
			mTvUserChoice.setTextColor(Color.BLACK);
		}
		for(int i = 0; i < answer.size(); i++) {
			if(answer.get(i).isCorrect()) {
				correct_answer_content.append(INDEX[i]).append("、");
			}
		}
		correct_answer_content.deleteCharAt(correct_answer_content.length() - 1);
		mTvCorrectAns.setText("正确答案：" + correct_answer_content);
	}
	
	private void errorExam() {
		Exam errorExma = new Exam();
		for(Question q : mExam.getQuestions()) {
			if(!q.isBlank() && !q.isCorrect()) {
				Question newq = new Question();
				newq.setId(q.getId());
				newq.setSubjectId(q.getSubjectId());
				newq.setContent(q.getContent());
				newq.setType(q.getType());
				newq.setTypeName(q.getTypeName());
				newq.setRequired(q.getRequired());
				newq.setAnswer(q.getAnswer());
				errorExma.getQuestions().add(newq);
			}
		}
		Intent i = new Intent(ExamResultDetailActivity.this, ErrorExamActivity.class);
		Bundle bundle = new Bundle();
		bundle.putParcelable("exam", errorExma);
		i.putExtras(bundle);
		startActivity(i);
		finish();
	}
	
}
